import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Modal, message, Space } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import * as allIcons from '@ant-design/icons/es';
import { queryModule, updateModule, addModule, removeModule, queryModuleTree, batchRemoveModules } from '@/services/module';
const { confirm } = Modal;


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addModule(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    console.log(await updateModule(fields));


    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    console.log(error)
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (record: API.ModuleItem) => {
  const hide = message.loading('正在删除');

  try {
    await removeModule({ moduleId: record.moduleId });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [treeData, setTreeData] = useState<API.TreeNodeItem[]>();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '名称',
      dataIndex: 'moduleName',
    },
    {
      title: '路径',
      dataIndex: 'relativePath',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '图标',
      dataIndex: 'iconClass',
      hideInSearch: true,
      renderText: (icon: string) => {
        const NewIcon = allIcons[icon] || allIcons[''.concat(icon, 'Outlined')];
        if (NewIcon) {
          return React.createElement(NewIcon);
        }
        return icon;
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'disable',
      hideInSearch: true,
      valueEnum: {
        0: { text: '启用', status: 'Success' },
        1: { text: '禁用', status: 'Error' },
      },
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'updateTime',
    //   valueType: 'dateTime',
    //   hideInSearch: true,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  useEffect(() => {
    async function queryTreeData() {
      setTreeData(await queryModuleTree({ type: 'root' }));
    }
    queryTreeData();
  }, []);

  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

  const onSelectChange = async (sKeys:any) => {
    setSelectedRowKeys(sKeys);
  };

  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveModules({ ids: selectedRowKeys.join(',') });
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };
  return (
    <>
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="moduleId"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a onClick={() => {
                confirm({
                  title: '您确定要批量删除吗?',
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    await batchRemove();
                    actionRef.current?.reload();
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }} >批量删除</a>
              {/* <a>导出数据</a> */}
            </Space>
          );
        }}
        options={false}
        request={(params) => queryModule({...params, current: 1, pageSize: 100, parentId:0})}
        columns={columns}
        pagination={false}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={treeData}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          treeData={treeData}
        />
      ) : null}
    </>
  );
};

export default TableList;
